package io.openkunlun.javadsl.springboot3.client;

import io.openkunlun.javarpc.RpcStub;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.util.List;
import java.util.stream.Collectors;

public class DaprStubFactoryBean implements FactoryBean<RpcStub>, ApplicationContextAware {

    private final Class<RpcStub> type;
    private final List<Class<?>> fields;
    private ApplicationContext applicationContext;

    public DaprStubFactoryBean(Class<RpcStub> type, List<Class<?>> fields) {
        this.type = type;
        this.fields = fields;
    }

    @Override
    public RpcStub getObject() throws Exception {
        List<Object> params = fields.stream().map(it -> applicationContext.getBean(it)).collect(Collectors.toList());
        RpcStub instance = this.type.getDeclaredConstructor(fields.toArray(new Class<?>[]{})).newInstance(params.toArray(new Object[]{}));
        applicationContext.getAutowireCapableBeanFactory().autowireBean(instance);
        return instance;
    }

    @Override
    public Class<?> getObjectType() {
        return type;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

}
